package com.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

@SuppressWarnings("deprecation")
public class WebChatUtil {
	// 公众号标识
	public static final String WXAPPID = GetConfig.getString("appId");
	public static final String SECRET = GetConfig.getString("appSecret");
	// 微信支付标识
	// private static final String MCH_ID = "1287947701"; // 商户号
	// public static final String KEY = "EFA8C72C559F4D3CB9C468843BC234E5"; //
	// 秘钥
	// private static final String KEY_FILE = "D://apiclient_cert.p12"; //证书

	/**
	 * 【注意】 1.网页授权网页授权access_token 是一次性的 基础支持的access_token的是有时间限制的：7200s
	 * 2.网页授权access_token 只能获取到一个微信用户信息，是与微信用户一对一的关系
	 * 基础支持的access_token，在有效期内就可以使用access_token和openId 获取微信用户信息
	 * 3.网页授权access_token没有次数限制
	 */

	/**
	 * 获取openId getOAuthAccessToken() OAuth2.0的获取accesstoken 获取用户授权 openid
	 */
	public static JsonObject getOAuth2(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAPPID + "&secret=" + SECRET
				+ "&code=" + code + "&grant_type=authorization_code";
		JsonObject json = httpRequestGet(url);
		if (json.get("errcode") != null) {
			System.out.println("============获得OAuth2.0 accesstoken失败" + json.get("errcode"));
			return null;
		} else {
			return json;
		}
	}

	/**
	 * 获取用户详细信息
	 */
	public static JsonObject getUserInfo(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAPPID + "&secret=" + SECRET
				+ "&code=" + code + "&grant_type=authorization_code";
		JsonObject json = httpRequestGet(url);
		if (json == null) {
			return null;
		} else {
			if (json.get("errcode") != null) {
				System.out.println("============获得OAuth2.0 accesstoken失败" + json.get("errcode"));
				return null;
			} else {
				String openId = json.get("openid").getAsString();
				String access_token = json.get("access_token").getAsString();
				String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid="
						+ openId + "D&lang=zh_CN";
				JsonObject userInfpJson = httpRequestGet(userUrl);
				if (userInfpJson != null) {
					userInfpJson.addProperty("openid", openId);
					if (userInfpJson.get("errcode") != null) {
						System.out.println("============获得userInfo失败" + json.get("errcode"));
						return userInfpJson;
					} else {
						return userInfpJson;
					}
				} else {
					return null;
				}
			}
		}
	}

	/**
	 * 获取js token
	 */
	public static String getJsTokenByHT() {
		String url = "Logistics/MEM/GetAccessToken";
		Map<String, Object> param = HttpClientUtil.getComMap("100", "", "");
		String tokenjson = HttpClientUtil.doPostWithJsonResult(url, param);
		Map<String,Object> map=GsonUtil.fromJson(tokenjson,new TypeToken<Map<String, Object>>(){}.getType());
		if(map.get("stateID")!=null && (Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0){
			return (String)map.get("AccessToken");
		}
		return null;
	}

	/**
	 * 获取js token
	 */
	public static String getJsToken() {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WXAPPID
				+ "&secret=" + SECRET;
		JsonObject json = httpRequestGet(url);
		if (json.get("access_token") != null && !"".equals(json.get("access_token").getAsString())) {
			return json.get("access_token").getAsString();
		} else {
			System.out.println("============获得accesstoken失败" + json.get("errcode"));
			return null;
		}

	}

	/**
	 * 获取js Ticket
	 */
	public static String getJsTicket(String token) {
		String jsurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
		JsonObject jsjson = httpRequestGet(jsurl);
		if (jsjson.get("ticket") != null && !"".equals(jsjson.get("ticket").getAsString())) {
			return jsjson.get("ticket").getAsString();
		} else {
			System.out.println("============获得js失败" + jsjson.get("errcode"));
			return null;
		}
	}

	/**
	 * 获取js Ticket
	 */
	public static String getJsTicket() {
		String token = getJsToken();
//		String token = getJsTokenByHT();
		if (token == null) {
			System.out.println("============获得accesstoken失败================");
			return null;
		}
		return getJsTicket(token);
	}

	public static Map<String, String> getJsapi(String url) {
		String jsapi_ticket = getJsTicket();
		Map<String, String> ret = new HashMap<String, String>();
		String noncestr = UUID.randomUUID().toString();
		String timestamp = create_timestamp();
		String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
				+ url;
		String signature = "";
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
		ret.put("appId", WXAPPID);
		ret.put("nonceStr", noncestr);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	/**
	 * 通用http调用微信请求 httpRequestGet()
	 */
	@SuppressWarnings("resource")
	public static JsonObject httpRequestGet(String url) {
		JsonObject json = new JsonObject();
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
		try {
			HttpResponse res = client.execute(get);
			String responseContent = null; // 响应内容
			HttpEntity entity = res.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
			json = jsonparer.parse(responseContent).getAsJsonObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接 ,释放资源
			client.getConnectionManager().shutdown();
		}
		return json;
	}

}